<template>
  <div class="app-container">

    <!-- 查询条件 -->
    <el-form size="small" :inline="true" :model="queryParam" class="demo-form-inline">
      <el-form-item label="商品名称">
        <el-input v-model="queryParam.name" placeholder="商品名称" />
      </el-form-item>

      <el-form-item label="状态">
        <el-select v-model="queryParam.isgrounding" clearable placeholder="状态">
          <el-option
            v-for="item in shelfList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="btnSearch">查询</el-button>
      </el-form-item>
    </el-form>

    <!-- 工具栏 -->

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd()">新增</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate()">修改</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete()">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini">导出</el-button>
      </el-col>
    </el-row>

    <el-table :data="tableData.rows" border style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column prop="id" label="编号" width="80" />
      <el-table-column prop="enterpriseName" label="商家名称" width="260" :show-overflow-tooltip="true" />
      <el-table-column prop="categoryName" label="分类名称" width="200" :show-overflow-tooltip="true" />
      <el-table-column prop="name" label="商品名称" width="250" :show-overflow-tooltip="true" />

      <el-table-column label="商品图片" width="160">
        <template slot-scope="scope">
          <img v-if="scope.row.picture" :src="scope.row.picture" width="150">
          <el-tag v-else type="danger">未上传图像</el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="price" label="商品价格" width="100" />

      <el-table-column label="状态" width="120">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.isgrounding===1" type="primary">上架</el-tag>
          <el-tag v-else type="danger">下架</el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页条 -->
    <el-pagination
      v-if="tableData.total>0"
      :current-page="queryParam.page"
      :page-sizes="[1, 5, 10, 20,30,50,100]"
      :page-size="queryParam.size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="tableData.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 新增和修改对话框-->
    <el-dialog :title="title" :visible.sync="open" width="1100px" append-to-body :close-on-click-modal="false" :before-close="cancelForm">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="菜品名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入菜品名称" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="菜品分类" prop="mid">
              <el-select v-model="form.mid" placeholder="请选择">
                <el-option
                  v-for="item in categoryList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>

            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="菜品价格" prop="price">
              <el-input v-model="form.price" placeholder="请输入菜品价格" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.isgrounding">
                <el-radio
                  v-for="dict in shelfList"
                  :key="dict.value"
                  :label="dict.value"
                >{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="口味配置">
              <div v-if="form.dishFlavors" class="flavorBox">
                <!-- 商品本身没有口味数据 -->
                <el-button v-if="form.dishFlavors.length == 0" type="warning" class="addBut" @click="addFlavor()">+添加口味</el-button>

                <!--商品本身有口味-->
                <div v-if="form.dishFlavors.length != 0" class="flavor">
                  <div class="title">
                    <span>口味名（3个字内）</span>
                    <span class="kwbq">口味标签（输入标签回车添加）</span>
                  </div>
                  <div v-for="(item ,index ) in form.dishFlavors" class="cont">
                    <!--口味名称 -->
                    <el-autocomplete
                      v-model="item.name"
                      class="inline-input"
                      :fetch-suggestions="querySearch"
                      placeholder="请输入内容"
                      :maxlength="3"
                      show-word-limit
                      @select="handleSelect"
                    >
                      <template slot-scope="{ item }">
                        <span>{{ item }}</span>
                      </template>
                    </el-autocomplete>

                    <!-- 口味明细 -->
                    <div class="labItems">
                      <el-tag v-for="(tag,ind) in item.value" :key="tag" closable :disable-transitions="false" @close="handleClose(item,ind)">
                        {{ tag }}
                      </el-tag>
                      <el-input
                        v-if="item.inputVisible"
                        ref="saveTagInput"
                        v-model="item.inputValue"
                        class="input-new-tag"
                        size="small"
                        @keyup.enter.native="handleInputConfirm(item)"
                        @blur="handleInputConfirm(item)"
                      />
                      <el-button v-else class="button-new-tag" size="small" @click="showInput(item)">+ New Tag</el-button>

                    </div>

                    <span class="delFlavor delBut non" @click="delFlavor(index)">删除</span>

                  </div>

                  <el-button type="warning" @click="addFlavor()">添加口味</el-button>

                </div>
              </div>

            </el-form-item>
          </el-col>

        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="菜品图片" prop="picture">
              <el-upload
                class="avatar-uploader"
                :action="imageUploadUrl"
                :show-file-list="false"
                :headers="headers"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="form.picture" :src="form.picture" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon" />
              </el-upload>
              <div style="display:none;">
                <el-input v-model="form.picture" style="width:0;height:0;" />
              </div>
            </el-form-item>
          </el-col>

        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="菜品描述">
              <el-input
                v-model="form.description"
                type="textarea"
                placeholder="请输入内容"
              />
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancelForm">取 消</el-button>
      </div>

    </el-dialog>

  </div>
</template>

<script>
import PageMinix from '@/mixin/PageMixin.js'
import AddOrEditMixin from '@/mixin/AddOrEditMixin.js'
import { commonDataApi, commonGoodsflavor } from '@/api/commonData.js'
import { dataListApi, findById, addApi, editApi } from '@/api/product.js'
import { findByMid } from '@/api/category.js'
export default {
  mixins: [PageMinix, AddOrEditMixin],
  data() {
    return {
      fetchDataApi: dataListApi,
      findByIdApi: findById,
      addApi: addApi,
      editApi: editApi,
      primaryKey: 'id',
      shelfList: [],
      // 口味
      flavorList: [],
      // 菜品分类
      categoryList: [],
      rules: {
        name: [
          { required: true, message: '该值不能为空', trigger: 'blur' }
        ],
        mid: [
          { required: true, message: '该值不能为空', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '该值不能为空', trigger: 'blur' }
        ],
        picture: [
          { required: true, message: '该值不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.initFormValue()
    this.fetchCommonData()
  },
  methods: {
    fetchCommonData() {
      commonDataApi().then(resp => {
        this.shelfList = resp.data.shelfData
      })

      // 读取商品分类
      findByMid().then(resp => {
        this.categoryList = resp.data
      })

      // 读取口味列表
      commonGoodsflavor().then(resp => {
        this.flavorList = resp.data
      })
    },
    // 表单初始化值
    initFormValue() {
      this.form = {
        picture: undefined,
        isgrounding: 0,
        // 口味列表
        dishFlavors: []
      }
    },
    // 图片上传成功以后返回的数据(json, file[blob]数据)
    handleAvatarSuccess(res, file) {
      this.form.picture = 'http://localhost:8080' + res.data.image
    },
    // 添加口味信息
    addFlavor() {
      if (this.form.dishFlavors.filter(p => p.name === '').length === 0) {
        this.form.dishFlavors.push({ name: '', value: [], inputVisible: false, inputValue: '' })
      } else {
        this.$message.error('口味还没有配置完成，不能添加新口味')
      }
    },
    // 口味搜索建议  https://element.eleme.cn/#/zh-CN/component/input#dai-shu-ru-jian-yi
    querySearch(queryString, cb) {
      var arr = this.flavorList
      // 调用 callback 返回建议列表的数据
      var results = queryString ? arr.filter(p => p.name.startsWith(queryString)) : arr
      var mapValue = results.map(p => p.name)
      console.log(mapValue)
      cb(mapValue)
    },
    // 自动建议选中
    handleSelect(item) {
      // 判断是否在口味集合中 this.form.dishFlavors：[ {name:'',value:[],inputVisible:false,inputValue:''}]
      if (item) {
        var result = this.flavorList.filter(p => p.name === item)
        // 得到表单中最后一个口味对象
        var findObj = this.form.dishFlavors.filter(p => p.name === undefined || p.name === item)
        if (findObj.length > 1) {
          this.$message.error('已经存在相同的口味名!')
        } else {
          var obj = findObj[0]
          obj.name = item
          // 在里面
          if (result.length > 0) {
            obj.value = result[0].value
          }
        }
      }
    },
    // 移出动态tags, 删除数组中的位置的值 item={name:'',value:[],inputVisible:false,inputValue:''}
    handleClose(item, index) {
      item.value.splice(index, 1)
    },
    // 点击动态添加tags
    showInput(item) {
      item.inputVisible = true
    },
    // 保存动态添加tags
    handleInputConfirm(item) {
      if (item.value.length >= 6) {
        this.$message.error('口味标签不能超过6个')
      } else {
        const inputValue = item.inputValue
        if (inputValue) {
          item.value.push(inputValue)
        }
      }

      item.inputVisible = false
      item.inputValue = ''
    },

    // 根据下标删除form的口味
    delFlavor(index) {
      this.form.dishFlavors.splice(index, 1)
    }
  }
}
</script>

<style scoped>
  .avatar-uploader{
     width: 178px;
     overflow: hidden;
  }

  .avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
      border-color: #409EFF;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }
    .avatar {
      width: 178px;
      height: 178px;
      display: block;

    }

    .el-tag + .el-tag {
        margin-left: 10px;
      }
      .button-new-tag {
        margin-left: 10px;
        height: 32px;
        line-height: 30px;
        padding-top: 0;
        padding-bottom: 0;
      }
      .input-new-tag {
        width: 90px;
        margin-left: 10px;
        vertical-align: bottom;
      }

   .flavorBox .flavor {
     border: solid 1px #dfe2e8;
     border-radius: 3px;
     padding: 15px;
     background: #fafafb;
   }
   .flavorBox .flavor .title {
     color: #606168;
   }

   .flavor .el-autocomplete {
      width: 150px;
   }

   .flavorBox .flavor .cont .labItems {
     display: inline-block;
     border-radius: 3px;
     min-height: 39px;
     border: solid 1px #d8dde3;
     background: #fff;
     padding: 0 5px;
     margin-left: 10px;
   }

   .flavorBox .flavor .cont  .delFlavor {
     display: inline-block;
     padding: 0 10px;
     color: #f19c59;
     cursor: pointer;
   }

   .flavorBox .flavor .cont {
     margin: 10px 0;
   }
   .flavorBox .title   .kwbq{
      margin-left: 45px;
   }
</style>
